package com.zhq.zhq_blog.module.blog.activity

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import com.zhq.zhq_blog.R
import com.zhq.zhq_blog.base.BaseActivity
import com.zhq.zhq_blog.databinding.ActivityPreviewBlogBinding

class PreviewBlogActivity : BaseActivity() {
    val mViewBinding by lazy { ActivityPreviewBlogBinding.inflate(layoutInflater) }
    private var pageFinish = false

    private fun initView(){
        mViewBinding.toolbar.title = "预览"
        setSupportActionBar(mViewBinding.toolbar)
        configWebView()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
    }

    override fun setContentView() {
        setContentView(mViewBinding.root)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.exit_fragment_menu,menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.edit -> finish()
        }
        return true
    }

    private fun configWebView() {
        val webSettings: WebSettings = mViewBinding.markdownContent.settings
        webSettings.javaScriptEnabled = true
        webSettings.domStorageEnabled = true
        webSettings.defaultFontSize = 16
        mViewBinding.markdownContent.isVerticalScrollBarEnabled = false
        mViewBinding.markdownContent.isHorizontalScrollBarEnabled = false
        mViewBinding.markdownContent.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress == 100) {
                    pageFinish = true
                    val content = intent.getStringExtra("content").toString()
                    loadMarkdown(content)
                }
            }
        }
        mViewBinding.markdownContent.loadUrl("file:///android_asset/markdown.html")
    }

    private fun loadMarkdown(markdown: String) {
        if (pageFinish) {
            val content = markdown.replace("\n", "\\n").replace("\"", "\\\"")
                .replace("'", "\\'")
            mViewBinding.markdownContent.evaluateJavascript("javascript:parseMarkdown(\"$content\");", null)
        }
    }
}